package com.xrj4j.k_tally.view

import android.annotation.SuppressLint
import android.os.Looper
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Divider
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.xrj4j.k_tally.LocalNavController
import com.xrj4j.k_tally.db.AppDatabase
import com.xrj4j.k_tally.db.IncomeList
import com.xrj4j.k_tally.db.OutcomeList
import com.xrj4j.k_tally.model.BillItem
import com.xrj4j.k_tally.model.IconType
import com.xrj4j.k_tally.model.Kind
import com.xrj4j.k_tally.navigation.NavScreen
import com.xrj4j.k_tally.utils.DateUtil
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

@SuppressLint("MutableCollectionMutableState")
@Composable
fun EditScreen(
    modifier: Modifier = Modifier,
    billItem: BillItem = BillItem(null)
) {

    EditTabGrid(
        billItem = billItem
    )
}

@OptIn(DelicateCoroutinesApi::class)
@Composable
fun EditTabGrid(
    billItem: BillItem
) {
    val item by remember {
        mutableStateOf(billItem)
    }
    var selectType by remember {
        val type = if (item.id == null) {
            if (item.kind == 0) OutcomeList[0] else IncomeList[0]
        } else {
            val typeList = if (item.kind == Kind.OUTCOME.code) OutcomeList else IncomeList
            val typeOptional = typeList.stream().filter { it.name == item.typeName }.findFirst()
            typeOptional.get()
        }
        mutableStateOf(type)
    }
    var tabIndex by remember { mutableIntStateOf(0) }
    val context = LocalContext.current
    val billDao = AppDatabase.getInstance(context).getBillDao()
    val navController = LocalNavController.current
    Column {
        TabRow(selectedTabIndex = tabIndex) {
            Tab(selected = tabIndex == 0, onClick = {
                tabIndex = 0
                selectType = OutcomeList[0]
            }) {
                Text(
                    text = "支出",
                    modifier = Modifier.padding(vertical = 10.dp),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
            Tab(selected = tabIndex == 1, onClick = {
                tabIndex = 1
                selectType = IncomeList[0]
            }) {
                Text(text = "收入")
            }
        }

        CurrentItem(
            item = item,
            selectType = selectType,
            onImeAction = { text, key ->
                var success = false
                // 检查键盘输入
                try {
                    when (key) {
                        "money" -> {
                            item.money = text.toFloat()
                        }

                        "remark" -> {
                            item.remark = text
                        }
                    }
                    success = true
                } catch (e: Exception) {
                    toast(context, "金额只能输入数字")
                }
                success
            }
        )

        LazyVerticalGrid(
            columns = GridCells.Fixed(5),
            contentPadding = PaddingValues(10.dp)
        ) {
            if (tabIndex == 0) {
                items(OutcomeList) {
                    EditGridItem(it, it == selectType) {
                        selectType = it
                    }
                }
            } else {
                items(IncomeList) {
                    EditGridItem(it, it == selectType) {
                        selectType = it
                    }
                }
            }
        }
    }
    Box(
        modifier = Modifier
            .padding(bottom = 25.dp, end = 20.dp)
            .fillMaxSize()
            .wrapContentSize(align = Alignment.BottomEnd)
    ) {
        FloatingActionButton(
            onClick = {
                GlobalScope.launch {
                    Looper.prepare();
                    try {
                        val itemTemp = item.copy(
                            typeIcon = selectType.iconSelected,
                            typeName = selectType.name,
                            kind = tabIndex
                        )
                        billDao.insert(itemTemp)
                        toast(context, "保存成功")
                        Looper.loop()

                    } catch (e: Exception) {
                        Log.e("sql", e.message!!)
                        toast(context, "保存失败")
                        Looper.loop()
                    }
                }
                navController.navigate(NavScreen.HOME.route)
            },
            shape = CircleShape
        ) {
            Icon(imageVector = Icons.Default.Check, contentDescription = null)
        }
    }

}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun CurrentItem(
    item: BillItem,
    selectType: IconType,
    onImeAction: (String, String) -> Boolean,
) {
    var text by remember { mutableStateOf(if (item.money > 0) item.money.toString() else "") }
    var remark by remember { mutableStateOf(item.remark) }
    var createTime by remember { mutableStateOf(item.createTime) }
    // 获取键盘控制器
    val keyboardController = LocalSoftwareKeyboardController.current

    // 类型和金额
    Row(
        modifier = Modifier
            .padding(start = 10.dp)
            .height(40.dp)
            .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {

        Row(
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = "类型: ",
                style = MaterialTheme.typography.titleMedium
            )
            Icon(
                painter = painterResource(id = selectType.iconSelected),
                contentDescription = null,
                modifier = Modifier
                    .size(50.dp)
                    .padding(start = 10.dp, end = 5.dp),
                tint = Color.Unspecified
            )
            Text(text = selectType.name)
        }
        Row(
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(text = "金额: ", style = MaterialTheme.typography.titleMedium)
            BasicTextField(
                value = text,
                onValueChange = { text = it },
                singleLine = true,
                // 配置软键盘点击完成时触发onImeAction函数并隐藏软键盘
                keyboardOptions = KeyboardOptions.Default.copy(
                    imeAction = ImeAction.Done,
                    keyboardType = KeyboardType.Number
                ),
                keyboardActions = KeyboardActions(onDone = {
                    // 触发函数检测键盘的整体输入
                    if (onImeAction(text, "money")) {
                        // 隐藏软键盘
                        keyboardController?.hide()
                    }
                })
            )
        }

    }

    // 备注编辑项
    Row(
        modifier = Modifier
            .padding(start = 10.dp)
            .height(40.dp)
            .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(text = "备注: ", style = MaterialTheme.typography.titleMedium)
        BasicTextField(
            value = remark,
            onValueChange = { remark = it },
            singleLine = true,
            // 配置软键盘点击完成时触发onImeAction函数并隐藏软键盘
            keyboardOptions = KeyboardOptions.Default.copy(
                imeAction = ImeAction.Done,
                keyboardType = KeyboardType.Text
            ),
            keyboardActions = KeyboardActions(onDone = {
                // 触发函数检测键盘的整体输入
                if (onImeAction(text, "remark")) {
                    // 隐藏软键盘
                    keyboardController?.hide()
                }
            })
        )
    }

    var showDatePicker by remember { mutableStateOf(false) }

    // 时间
    Row(
        modifier = Modifier
            .padding(start = 10.dp)
            .height(40.dp)
            .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(text = "时间: ", style = MaterialTheme.typography.titleMedium)
        Text(
            text = createTime,
            modifier = Modifier.clickable { showDatePicker = true },
            style = MaterialTheme.typography.bodyMedium
        )
        DatePicker(
            show = showDatePicker,
            initData = DateUtil.parseDate(createTime),
            onDateSelected = {
                createTime = DateUtil.formatDate(it)
            },
            onCanceled = { showDatePicker = false }
        )
    }
    Divider()
}

@Composable
fun EditGridItem(
    type: IconType,
    selected: Boolean = false,
    onClick: () -> Unit
) {
    Log.d("xrj4j", "333")
    Column(
        modifier = Modifier
            .padding(top = 10.dp)
            .clickable { onClick() },
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Icon(
            painter = painterResource(id = if (selected) type.iconSelected else type.icon),
            contentDescription = null,
            modifier = Modifier.size(30.dp),
            tint = Color.Unspecified
        )
        Text(text = type.name)
    }
}